package com.joe.codemother.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.joe.codemother.constant.LoginConstant;
import com.joe.codemother.entity.dto.UserQueryRequest;
import com.joe.codemother.entity.enums.UserRoleEnums;
import com.joe.codemother.entity.vo.UserLoginVo;
import com.joe.codemother.entity.vo.UserVo;
import com.joe.codemother.exception.BusinessException;
import com.joe.codemother.exception.ErrorCode;
import com.joe.codemother.service.ValidateService;
import com.joe.codemother.util.ThrowUtils;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.joe.codemother.entity.User;
import com.joe.codemother.mapper.UserMapper;
import com.joe.codemother.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户 服务层实现。
 *
 * @author joe
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>  implements UserService{

    @Resource
    private ValidateService  validateService;


    @Override
    public long userRegister(String username, String password, String confirmPassword) {
        validateService.validateRegister(username, password, confirmPassword);
        String encryptedPassword = getEncryptedPassword(password);
        User user = new User();
        user.setUserAccount(username);
        user.setUserPassword(encryptedPassword);
        user.setUserName("default");
        user.setUserRole(UserRoleEnums.User.getRoleValue());
        log.info("user register user:{}", user);
        boolean save = this.save(user);
        ThrowUtils.throwIf(!save,new BusinessException(ErrorCode.SYSTEM_ERROR,"REGISTER_ERROR"));
        return user.getId();
    }

    @Override
    public UserLoginVo userLogin(String username, String password, HttpServletRequest request) {
        ThrowUtils.throwIf(ObjectUtil.hasEmpty(username, password, request),new BusinessException(ErrorCode.SYSTEM_ERROR,"USERNAME_OR_PASSWORD_ERROR"));

        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("userAccount",username);
        wrapper.eq("userPassword",this.getEncryptedPassword(password));
        User user = this.mapper.selectOneByQuery(wrapper);
        ThrowUtils.throwIf(user == null,new BusinessException(ErrorCode.SYSTEM_ERROR,"USER_NOT_EXIST"));
        UserLoginVo userLoginVo = this.convertUserToVo(user);
        request.getSession().setAttribute(LoginConstant.LOGIN_USER,userLoginVo);
        return userLoginVo;
    }

    @Override
    public User getLoginUser(HttpServletRequest request) {
        ThrowUtils.throwIf(request == null, new BusinessException(ErrorCode.PARAMS_ERROR));
        Object user = request.getSession().getAttribute(LoginConstant.LOGIN_USER);
        UserLoginVo currentUser = (UserLoginVo) user;
        ThrowUtils.throwIf((ObjectUtil.isEmpty(currentUser) || currentUser.getId() == null),new BusinessException(ErrorCode.SYSTEM_ERROR,"not login or there is some problem"));
        long id = currentUser.getId();
        User refreshUser = this.mapper.selectOneById(id);
        if(ObjectUtil.isEmpty(refreshUser)){
            throw  new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        return refreshUser;
    }

    @Override
    public String getEncryptedPassword(String password) {
            final String SALT = "joe";
            return DigestUtils.md5DigestAsHex((SALT + password).getBytes());
        }

    public UserLoginVo convertUserToVo(User user) {
        if (user == null) {
            return null;
        }
        UserLoginVo userLoginVo = new UserLoginVo();
        BeanUtil.copyProperties(user, userLoginVo);
        return userLoginVo;
    }

    @Override
    public boolean userLogOut(HttpServletRequest request) {
        Object loginUser = request.getSession().getAttribute(LoginConstant.LOGIN_USER);
        ThrowUtils.throwIf(ObjectUtil.isEmpty(loginUser),new BusinessException(ErrorCode.SYSTEM_ERROR,"no login or system error!"));
        request.getSession().removeAttribute(LoginConstant.LOGIN_USER);
        return true;
    }

    @Override
    public UserVo getUserVo(User user) {
        if (user == null) {
            return null;
        }
        UserVo userVo = new UserVo();
        BeanUtil.copyProperties(user, userVo);
        return userVo;
    }

    @Override
    public List<UserVo> getUserVoList(List<User> userList) {
        if (CollUtil.isEmpty(userList)) {
            return new ArrayList<>();
        }
        return userList.stream().map(this::getUserVo).collect(Collectors.toList());
    }

    @Override
    public QueryWrapper getQueryWrapper(UserQueryRequest userQueryRequest) {
        if (userQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        Long id = userQueryRequest.getId();
        String userAccount = userQueryRequest.getUserAccount();
        String userName = userQueryRequest.getUserName();
        String userProfile = userQueryRequest.getUserProfile();
        String userRole = userQueryRequest.getUserRole();
        String sortField = userQueryRequest.getSortField();
        String sortOrder = userQueryRequest.getSortOrder();
        return QueryWrapper.create()
                .eq("id", id)
                .eq("userRole", userRole)
                .like("userAccount", userAccount)
                .like("userName", userName)
                .like("userProfile", userProfile)
                .orderBy(sortField, "ascend".equals(sortOrder));
    }


}
